﻿using DotNetCore.CAP;
using Jinjia.Core.Transaction.Extension;
using Jinjia.Core.Transaction.Model;
using Jinjia.Core.Transaction.Service;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;

namespace Jinjia.Core.TransactionServiceExtensions
{
    public static class TransactionServiceExtensions
    {
        private static IServiceCollection AddDistributedTransactionService(this IServiceCollection services)
        {
            services.TryAddEnumerable(ServiceDescriptor.Scoped<IDistributedTransactionService, DistributedTransactionService>());

            return services;
        }

        public static IServiceCollection AddCapService(this IServiceCollection services, IConfiguration configure, Action<CapOptions> capOption = null)
        {
            var transactionOptions = configure.Get<TransactionOptions>();

            AddDistributedTransactionService(services)
                .AddCap(conf =>
                {
                    capOption?.Invoke(conf);
                    conf.UseMySql(transactionOptions.CapMySqlDb);
                    conf.UseRabbitMQ(rabOption =>
                    {
                        rabOption.HostName = transactionOptions.CapTransport.HostName;
                        rabOption.Port = transactionOptions.CapTransport.Port;
                        rabOption.UserName = transactionOptions.CapTransport.UserName;
                        rabOption.Password = transactionOptions.CapTransport.Password;
                        rabOption.ExchangeName = transactionOptions.CapTransport.ExchangeName;
                        rabOption.VirtualHost = transactionOptions.CapTransport.VirtualHost;
                    });
                })
                .NotCreateDbTable();

            return services;
        }
    }
}